import React, { useState, useEffect } from 'react';
import moment from 'moment-timezone';
import axios from 'axios';
import { toast } from 'react-toastify';
import { useNavigate } from 'react-router-dom';
import './Notifications.css';

const CreateNotification = () => {
  const [formData, setFormData] = useState({
  recipientId: '',
  title: '',
  content: '',
  isRecurring: false,
  recurrenceType: '',
  recurrenceInterval: 1,
  startDateTime: ''
});
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const navigate = useNavigate();

  const { recipientId, title, content } = formData;

  // 加载员工列表
  useEffect(() => {
    const fetchEmployees = async () => {
      try {
        setLoading(true);
        const res = await axios.get('/users/employees');
        setEmployees(res.data || []);
      } catch (err) {
        console.error('获取员工列表失败', err);
        toast.error('获取员工列表失败，请刷新页面重试');
      } finally {
        setLoading(false);
      }
    };

    fetchEmployees();
  }, []);

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // 表单验证
    if (!recipientId || !title || !content) {
      return toast.error('请填写所有必填字段');
    }

    if (formData.isRecurring) {
      if (!formData.recurrenceType || !formData.recurrenceInterval || !formData.startDateTime) {
        return toast.error('请填写定时任务的所有字段');
      }

      const selectedDateTime = moment.tz(formData.startDateTime, 'YYYY-MM-DDTHH:mm', 'Asia/Shanghai').toDate();
      const now = moment.tz('Asia/Shanghai').toDate();
      if (selectedDateTime <= now) {
        return toast.error('开始时间必须大于当前时间');
      }
    }

    setSubmitting(true);
    try {
      const postData = { ...formData };
      if (formData.isRecurring) {
        const gmt8DateTime = moment.tz(formData.startDateTime, 'YYYY-MM-DDTHH:mm', 'Asia/Shanghai');
        postData.startDateTime = gmt8DateTime.utc().toISOString();
      }
      await axios.post('/notifications', postData);
      toast.success('任务创建成功');
      navigate('/notifications');
    } catch (err) {
      console.error('发送通知失败', err);
      toast.error(err.response?.data?.message || '创建任务失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return <div className="loading">加载员工列表中...</div>;
  }

  return (
    <div className="create-notification-container">
      <h1 className="page-title">创建新任务</h1>

      <form onSubmit={handleSubmit} className="notification-form">
        <div className="form-group">
          <label htmlFor="recipientId">接收员工</label>
          <select
            id="recipientId"
            name="recipientId"
            value={recipientId}
            onChange={handleChange}
            required
            className="form-control"
          >
            <option value="">-- 选择员工 --</option>
            {employees.map(employee => (
              <option key={employee.id} value={employee.id}>
                {employee.full_name || employee.username}
              </option>
            ))}
          </select>
        </div>

        <div className="form-group">
          <label htmlFor="title">任务标题</label>
          <input
            type="text"
            id="title"
            name="title"
            value={title}
            onChange={handleChange}
            required
            className="form-control"
          />
        </div>

        <div className="form-group">
          <label htmlFor="content">任务内容</label>
          <textarea
            id="content"
            name="content"
            value={content}
            onChange={handleChange}
            required
            rows="6"
            className="form-control"
          ></textarea>
        </div>

        <div className="form-group">
          <label>
            <input
              type="checkbox"
              name="isRecurring"
              checked={formData.isRecurring}
              onChange={handleChange}
            />
            创建定时任务
          </label>
        </div>

        {formData.isRecurring && (
          <>
            <div className="form-group">
              <label htmlFor="recurrenceType">定时类型</label>
              <select
                id="recurrenceType"
                name="recurrenceType"
                value={formData.recurrenceType}
                onChange={handleChange}
                required
                className="form-control"
              >
                <option value="">-- 选择定时类型 --</option>
                <option value="month">每月</option>
                <option value="week">每周</option>
                <option value="day">每天</option>
              </select>
            </div>

            <div className="form-group">
              <label htmlFor="recurrenceInterval">间隔 (n)</label>
              <input
                type="number"
                id="recurrenceInterval"
                name="recurrenceInterval"
                value={formData.recurrenceInterval}
                onChange={handleChange}
                min="1"
                required
                className="form-control"
              />
            </div>

            <div className="form-group">
              <label htmlFor="startDateTime">开始时间</label>
              <input
                type="datetime-local"
                id="startDateTime"
                name="startDateTime"
                value={formData.startDateTime}
                onChange={handleChange}
                required
                className="form-control"
              />
            </div>
          </>
        )}

        <div className="form-actions">
          <button
            type="submit"
            className="btn btn-primary"
            disabled={submitting}
          >
            {submitting ? '创建中...' : '创建任务'}
          </button>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/notifications')}
          >
            取消
          </button>
        </div>
      </form>
    </div>
  );
};

export default CreateNotification;